package cn.iocoder.yudao.module.fengdong.smartelderly.service.reserved;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.JsonUtils;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.QrCodeUtils;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.vo.ActivityRecordBaseVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xingyuv.jushauth.utils.UuidUtils;
import jodd.io.FileUtil;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;

import cn.iocoder.yudao.module.fengdong.smartelderly.controller.admin.reserved.vo.*;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.dataobject.reserved.ReservedDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.fengdong.smartelderly.convert.reserved.ReservedConvert;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.reserved.ReservedMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getTenantId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.fengdong.smartelderly.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.fengdong.smartelderly.utils.IdentityCardUtils.verifyIdentityCard;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 预约管理 Service 实现类
 *
 * @author 沣东养老院管理员
 */
@Service
@Validated
@Slf4j
public class ReservedServiceImpl implements ReservedService {

    @Resource
    private ReservedMapper reservedMapper;
    @Autowired
    QrCodeUtils qrCodeUtils;

    @Override
    public Long createReserved(ReservedCreateReqVO createReqVO) throws IOException {
        if (StringUtil.isNotBlank(createReqVO.getPhone())) {
            isValidContactInformation(createReqVO.getPhone());
        }
        if (StringUtil.isNotBlank(createReqVO.getIdentityCard())) {
            verifyIdentityCard(createReqVO.getIdentityCard());
        }
        // 插入
        log.info("用户 "+ getLoginUserId());
        ReservedDO reserved = ReservedConvert.INSTANCE.convert(createReqVO);
        if (reservedMapper.selectCountByTenMinute(createReqVO.getType(),getLoginUserId())>0) {
            throw exception(RESERVED_SUBMIT_AGAIN);
        }
        reservedMapper.insert(reserved);
        if (reserved.getType()!=null){
            ActivityRecordBaseVO recordBaseVO = new ActivityRecordBaseVO();
            recordBaseVO.setActivityKind(Long.valueOf(reserved.getType()));
            recordBaseVO.setReservedId(reserved.getId());
            if (reserved.getType()==1) {
                //访客
                recordBaseVO.setUserName(reserved.getName());
                recordBaseVO.setIdentityCard(reserved.getIdentityCard());
            } else if (reserved.getType()==2) {
                //探视
                recordBaseVO.setUserName(createReqVO.getName());
            }else if (reserved.getType()==3) {
                //老人请假
                recordBaseVO.setUserId(Long.valueOf(reserved.getOldmanId()));
            }
            getQrCodeLocaltest(recordBaseVO);//生成本地二维码 本地测试
            recordBaseVO.setTenantId(getTenantId());
            reserved.setOthers(qrCodeUtils.getQrCode(recordBaseVO));//插入string 二维码
        }
        // 返回
        return reserved.getId();
    }

    private void getQrCodeLocaltest(ActivityRecordBaseVO recordBaseVO) {
        String uuid = UuidUtils.getUUID();
        //生成二维码
        String content= JsonUtils.objToJson(recordBaseVO);
        File generate = QrCodeUtil.generate(
                content, //二维码数据
                300,
                300,
                FileUtil.file("c:/tp/"+uuid+".jpg"));
    }

    /**
     * 联系方式校验  只允许手机号
     * @param contactInformation
     */
    public static void isValidContactInformation(String contactInformation) {
        // 手机号正则表达式
        String phoneRegex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(16[5,6])|(17[0-8])|(18[0-9])|(19[1、5、8、9]))\\d{8}$";
        boolean ruslt = Pattern.matches(phoneRegex, contactInformation);
        if (!ruslt) {
            throw exception(PHONE_CONTACT_INFORMATION);
        }
    }
    @Override
    public void updateReserved(ReservedUpdateReqVO updateReqVO) {
        // 校验存在
        validateReservedExists(updateReqVO.getId());
        // 更新
        ReservedDO updateObj = ReservedConvert.INSTANCE.convert(updateReqVO);
        reservedMapper.updateById(updateObj);
    }

    @Override
    public void deleteReserved(Long id) {
        // 校验存在
        validateReservedExists(id);
        // 删除
        reservedMapper.deleteById(id);
    }

    private void validateReservedExists(Long id) {
        if (reservedMapper.selectById(id) == null) {
            throw exception(RESERVED_NOT_EXISTS);
        }
    }

    @Override
    public ReservedDO getReserved(Long id) {
        return reservedMapper.selectById(id);
    }

    @Override
    public List<ReservedDO> getReservedList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return reservedMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ReservedDO> getReservedPage(ReservedPageReqVO pageReqVO) {
        return reservedMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ReservedDO> getReservedList(ReservedExportReqVO exportReqVO) {
        return reservedMapper.selectList(exportReqVO);
    }

    @Override
    public IPage<ReservedAppRespVO> getAPPReservedPage(ReservedAppPageReqVO pageVO) {
        return  reservedMapper.getAPPReservedPage(MyBatisUtils.buildPage(pageVO),pageVO,getLoginUserId());
    }

    @Override
    public IPage<ReservedAppRespVO> getAPPReservedAllPage(ReservedAppPageReqVO pageVO) {
        return  reservedMapper.getAPPReservedAllPage(MyBatisUtils.buildPage(pageVO),pageVO,getLoginUserId());
    }

}
